package LeetCode.month02.day44;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class No56 {
    public int[][] merge(int[][] intervals) {
        int n = intervals.length;
        Arrays.sort(intervals,(a,b)->a[0]==b[0]?a[1]-b[1]:a[0]-b[0]);
        List<int[]> list = new ArrayList<>();
        for (int i = 0; i < n+1; i++) {
            int left = intervals[i][0];
            int right = intervals[i][1];
            if(list.isEmpty()||list.get(list.size()-1)[1]<left){
                list.add(new int[]{left,right});
            }else{
                list.set(list.size()-1,new int[]{list.get(list.size()-1)[0],Math.max(right,list.get(list.size()-1)[1])});
            }
        }
        return list.toArray(new int[list.size()][]);
    }
}
